package hot100;

/**
 * 208. 实现 Trie (前缀树)
 */
public class Trie {
    public TrieNode root;

    static class TrieNode {
        TrieNode[] children;
        boolean isEnd;

        public TrieNode() {
            children = new TrieNode[26];
            isEnd = false;
        }
    }

    public Trie() {
        root = new TrieNode();
    }

    public void insert(String word) {
        TrieNode node = root;
        for (char ch : word.toCharArray()) {
            int cur = ch - 'a';
            if (node.children[cur] == null) {
                node.children[cur] = new TrieNode();
            }
            node = node.children[cur];
        }
        node.isEnd = true;
    }

    public boolean search(String word) {
        TrieNode node = root;
        for (char ch : word.toCharArray()) {
            if (node.children[ch - 'a'] == null) {
                return false;
            } else {
                node = node.children[ch - 'a'];
            }
        }
        return node.isEnd;
    }

    public boolean startsWith(String prefix) {
        TrieNode node = root;
        for (char ch : prefix.toCharArray()) {
            if (node.children[ch - 'a'] == null) {
                return false;
            } else {
                node = node.children[ch - 'a'];
            }
        }
        return true;
    }
}
